/*
	用户列表管理
	功能：
		用户列表
		用户详情
		用户封停
		用户信息修改
*/

//登录信息
var adminLoginedInfo = Cookies.getJSON('kplus_ad_logined_info');
var tableInstance = undefined;
var filterData = undefined;
var tableIns = undefined;
var unChangePwdUser = [];
var changedPwdUser = [];
var userVipLevelNormal = 0, userVipLevelSilver = 0, userVipLevelGold = 0, userVipLevelDiamond = 0;

var userVipData = {
	'normal': [],
	'silver': [],
	'gold': [],
	'diamond': []
};

//处理表格数据
function dellTableData(data, get=true){

	var tableData = new Array();
	for (var i = 0; i < data.length; i++) {
		if(get){
			if(data[i].vip_level === 'normal'){
				userVipLevelNormal += 1;
				userVipData['normal'].push(data[i])
			}else if(data[i].vip_level === 'silver'){
				userVipLevelSilver += 1;
				userVipData['silver'].push(data[i])
			}else if(data[i].vip_level === 'gold'){
				userVipLevelGold += 1;
				userVipData['gold'].push(data[i])
			}else if(data[i].vip_level === 'diamond'){
				userVipLevelDiamond += 1;
				userVipData['diamond'].push(data[i])
			}
			// 处理未修改密码用户
			if(data[i].u_pwd === "669b93d09fdde4db4adaf17631c43b54"){
				unChangePwdUser.push(data[i])
			}else{
				changedPwdUser.push(data[i])
			}
		}

		$('#dataSize').text(data.length);
		
		var ary = {
			UID: data[i].u_id,
			username: data[i].u_name,
			sex: data[i].u_sex,
			birth: data[i].u_birthday,
			email: data[i].u_mail,
			phone: data[i].u_phone,
			regtime: formatTime(data[i].format_time),
			isvip: data[i].is_vip,
			vipLevel: data[i].vip_level,
			addr: data[i].u_addr
		};
		tableData.push(ary);
	};
    return tableData;
}

//dom加载完成
$(function(event){
	//使用layui
	layui.use(['laydate', 'layer', 'form','table'], function(){
		var laydate = layui.laydate,
			layer = layui.layer,
			form = layui.form,
			table = layui.table;

		//请求数据
		var ajaxData = {
			'aId': adminLoginedInfo.aId,
            'aToken': adminLoginedInfo.aToken,
            'status': '1', //状态正常
		}

		//生成表格
		function createTable(tableData){
			filterData = tableData;
			tableIns = table.render({
				elem: '#tableContent',
				id: "userDataTable",
				title: "KPLUS会员数据表格(基本)" + new Date().valueOf(),
				height: 620,
				limit: 30, //分页
				page: true,
				cols:[[ //表头
					{field: 'UID', title: 'UID', sort: true, fixed: 'left'},
					{field: 'username', title: '用户名'},
					{field: 'sex', title: '性别', sort: true, width: 80},
					{field: 'birth', title: '生日', sort: true} ,
					{field: 'email', title: '邮箱(登录凭据)'},
					{field: 'phone', title: '手机'},
					{field: 'vipLevel', title: '会员等级'},
					{field: 'regtime', title: '注册时间', sort: true},
					{field: 'isvip', title: '是否VIP', sort: true, width: 80},
					{field: 'addr', title: '地址'},
					{field: 'option', title: '操作', toolbar:'#toolbar'}
				]],
				data:tableData
			});
		}	

		//获取用户列表
		function getUserList(ajaxData){
			var loadIndex = layer.load(1, { shade: [0.5, '#000'] });
			$.ajax({
				url: BASE_SERVICEURL + URlS.au,
				type: 'GET',
				data: ajaxData,
				success: function(responseData){
					
					if(responseData.msg.code == 200){
						//console.log(responseData)
						var tb_data = dellTableData(responseData.data.data);
						//console.log(tb_data);
						createTable(tb_data);
						layer.close(loadIndex);
					}else{
						layer.close(loadIndex);
						layer.msg(MESSAGES.get_form_error + responseData.msg.msg, {time: 2000});
					}
				},
				error: function(responseData){
					layer.msg(MESSAGES.service_error, {time: 2000, end:function(){
						//导向500页面
						location.href = './500.html';
					}});
				}
			});
		}
		getUserList(ajaxData);


		//修改用户
		function modifyUserInfo(wantChangeData, obj){
			var loadIndex = layer.load(1, { shade: [0.5, '#000'] }); 
			var modifyData = $.extend(ajaxData, wantChangeData);
			$.ajax({
				url: BASE_SERVICEURL + URlS.au,
				type: 'POST',
				data: modifyData,
				success: function(responseData){
					if(responseData.msg.code == 200){
						//console.log(responseData);
						layer.close(loadIndex);
						layer.msg(MESSAGES.change_user_status_success , {time: 2000});
						//删除对应行（tr）的DOM结构，并更新缓存
						obj.del();
					}else{
						layer.close(loadIndex);
						layer.msg(responseData.msg.msg , {time: 2000});
					}
				},
				error: function(responseData){
					layer.close(loadIndex);
					layer.msg(MESSAGES.service_error , {time: 2000});
				}
			})
		}
		function deleteUser(wantDeleteData, obj){

			var loadIndex = layer.load(1, { shade: [0.5, '#000'] }); 
			var deleteData = $.extend(ajaxData, wantDeleteData);
			$.ajax({
				url: BASE_SERVICEURL + URlS.au,
				type: 'DELETE',
				data: deleteData,
				success: function(responseData){
					if(responseData.msg.code == 200){
						//console.log(responseData);
						layer.close(loadIndex);
						layer.msg("删除會員資訊成功！" , {time: 2000});
						//删除对应行（tr）的DOM结构，并更新缓存
						obj.del();
					}else{
						layer.close(loadIndex);
						layer.msg(responseData.msg.msg , {time: 2000});
					}
				},
				error: function(responseData){
					layer.close(loadIndex);
					layer.msg(MESSAGES.service_error , {time: 2000});
				}
			})
		}
		//监听工具table工具条
		table.on('tool(user-list-table)', function(obj){
			var data = obj.data;   //本行数据
			var layEvent = obj.event; 
			var tr = obj.tr;  //当前行
			if(layEvent === 'stop'){  // 停用
				layer.confirm(MESSAGES.stop_user, {btn: ['確認', '取消']}, function(){
					modifyUserInfo({uId: data.UID, status: '0'}, obj);
				}, function(){})
			}else if(layEvent === 'edit'){  //查看详情 编辑
				x_admin_show('查看详情', 'user-detail.html?uId='+data.UID+'', 1200, 600);
			}else if(layEvent === 'delete'){ // 删除会员
				layer.confirm("是否確認删除該會員？", {btn: ['確認', '取消']}, function(){
					deleteUser({uId: data.UID, status: '0'}, obj);
				}, function(){})
			}
		});
		// 监听过滤项
		form.on('select(queryFilter)', function(data){
			console.log(data.value); //得到被选中的值
			var loadIndex = layer.load(1, { shade: [0.5, '#000'] });
			var param = data.value;
			var tb_data = undefined;
			if(param == 'all'){
			  	getUserList(ajaxData);
			}
			if(param == 'normal'){
				tb_data = dellTableData(userVipData['normal'], false);
				dataType = 'normal';
			};
			if(param == 'vip'){
				tb_data = dellTableData($.extend(userVipData['silver'], userVipData['gold'], userVipData['diamond']), false);
				dataType = 'vip';
			};
			if(param == 'silver'){
				tb_data = dellTableData(userVipData['silver'], false);
				dataType = 'silver';
			};
			if(param == 'gold'){
				tb_data = dellTableData(userVipData['gold'], false);
				dataType = 'gold';
			};
			if(param == 'diamond'){
				tb_data = dellTableData(userVipData['diamond'], false);
				dataType = 'diamond';
			};
			if(param == "unChangePwd"){
				tb_data = dellTableData(unChangePwdUser, false);
			}
			if(param == "changedPwd"){
				tb_data = dellTableData(changedPwdUser, false);
			}
			createTable(tb_data);
			layer.close(loadIndex);
		});
		// 下载表格
		$('#downloadDataForCVS').on('click tap touch', function(){
			var cols = ['UID', '用户名', '性别', '生日', '邮箱(登录凭据)', '手机', '注册时间', '是否VIP', '会员VIP等级', '地址'];
			table.exportFile(tableIns.config.id, filterData, 'csv'); 
			return false;
		})
		//
		$('#openWindow').on('click tap touch', function(){
			x_admin_show('添加用户','./user-add.html')
		})
		//高级检索
		form.on('submit(sreach)', function(data){
			//console.log(data.field);
			var option = data.field;
			if(data.field.uName) option = { uName: data.field.uName }; //具体用户名存在的情况下 忽略时间检索
			//合并数据 并获取符合条件列表
			getUserList($.extend({}, ajaxData, option));
		})
	});
})





